<template>
 <div>
  <div class="produceBox">
    <div class="produceImg">
      <div class="bigImg" :v-model="goodNew.mainPictures">
     
    
        <img :src="i" alt="" v-for="(i,index) in goodNew.mainPictures" :key="i" v-show="CurrentIndex===index">
      </div>
      <ul class="small">
     
        <li v-for="(i,index) in goodNew.mainPictures" :key="i"
         :class="{active: CurrentIndex === index}"
        @mouseenter='showImg(index)'
        >
        
        <img :src="i" alt="">
        </li>
       
      </ul>
      <div class="goodsTag">
      <li>
      <p>热销人气</p>
      <span>200+</span>
      <p class="p2">热销人气</p>
      </li>
      <li>
      <p>热销人气</p>
      <span>200+</span>
      <p class="p2">热销人气</p>
      </li>
      <li>
      <p>收藏人气</p>
      <span>200+</span>
      <p class="p2">收藏商品</p>
      </li>
      <li>
      <p>品牌信息</p>
      <span>200+</span>
      <p class="p2">品牌信息</p>
      </li>
      </div>
     
    </div>
    <div class="produceMsg">
    <p class="p1">{{goodNew.name}}</p>
    <p class="p2">{{goodNew.desc}}</p>
    <p v-if='good.price'><span class="newPrice">{{good.price}}</span> <span class="olderPrice">{{good.oldPrice}}</span></p>
     <p v-else><span class="newPrice">{{goodNew.price}}</span> <span class="olderPrice">{{goodNew.oldPrice}}</span></p>
    <div class="MsgBox">
    <dl >
    <span>促销</span>
    <p>12月送好物，App领券购买直降120元</p>
    </dl>
    <dl><span>配送</span>
    <p>至
     <el-cascader
      v-model="value"
      :options="options"
      :props="props"
      @change="handleChange"
    />
    </p></dl>
    <dl><span>服务</span>
    <p class="service">
    <span>配送</span>
    <span>配送</span>
    <span>配送</span>
    </p></dl>
    </div>
    <!-- 规格 -->
     
    <div class="type" v-for="item in goodNew.specs"  :key="item.id">
    <span class="types" >{{item.name}}</span>
    <p class="box">
    <template v-for="i in item.values" 
    :key="i.name">
  <!-- 图片、span -->
    <img  
    :src="i.picture" alt="" 
    :class="{selected:i.selected,disabled:i.disabled}" 
    :title="i.name"
    v-if="i.picture"
    @click="changeSku(item,i)">
    <el-tag
      type=info
      :class="{selected:i.selected}"
     v-else  
     @click="changeSku(item,i)"
     >{{i.name}}
     </el-tag>
    </template>
     
    </p>
    </div>
     <div class="number">
    <span >数量</span>
    <p >
   <van-stepper v-model="number" integer @change='changNumber' />
    </p>
    </div>
    <p><el-button class="car" @click="addCar">加入购物车</el-button></p>
    </div>
  </div>
  <!-- 同款商品 -->
  <div class="info">
  <h2>同类商品推荐</h2>

  </div>
  <!-- 详情 -->
  <div class="goods-detal">
  <el-tabs  
  v-model="activeName" 
  class="demo-tabs" 
  @tab-click="handleClick">
  <!-- 商品详情 -->
    <el-tab-pane label="商品详情" name="first">
   
    <ul class="detail" >
   <!-- 商品详情 -->
    <li v-for="item in details.properties" :key="item.id">
    <span class="detail-tag">{{item.name}}</span>
    <span class="detail-msg">{{item.value}}</span>
    </li>
    </ul>
<div class="detail-img">

<template v-for="img in goodValue.details.pictures" :key="img"  >
  <img :src="img" alt="" >
</template>
</div>
    </el-tab-pane>
    <el-tab-pane label="商品评论" name="second">
    </el-tab-pane> 
  </el-tabs>
   <!-- <pre v-if='goodNew.details'>{{
        goodNew.details
    }}</pre> -->

  </div>
  <pre>
 
  </pre>
 </div>
  
</template>

<script setup>
import { useStore } from "vuex";
import {AddCart} from '@/api/http'
import { useRoute } from "vue-router";
import { GoodsInfo } from "@/api/http";
import powerSet from '@/vender/power-set'
// import GoodsSku from './good-sku.vue'

  const pathMap = {}
import { ref, computed, reactive, refs, mounted,onMounted } from "vue";
const spliter = '★'
import {
  Document,
  Menu as IconMenu,
  Location,
  Setting,
  Search,
  ArrowLeftBold ,
  ArrowRightBold
} from '@element-plus/icons-vue'

import {ElMessage} from 'element-plus'

const store = useStore();
const route = useRoute();
const details =ref([])
console.log("route.params.id", route.params.id);
const goodNew = ref([])
const spes= ref([])
const goodValue = reactive({
  details:[],
  skus:[]
})
const skus= ref([])
const value = ref([])
 const  CurrentIndex = ref(1)
 const showImg =(index) =>{
    console.log(index)
    CurrentIndex.value = index
 }

 const getGoodsInfo = async () => {
  const { data: res } = await GoodsInfo(route.params.id);
  console.log(res.result );

  goodNew.value =res.result 

  goodValue.details = res.result.details
  goodValue.skus  = res.result.skus
  skus.value = res.result.skus
  spes.value = res.result.specs
  // JSON.parse(JSON.stringify(goodNew.value)) 
  console.log('goodNew.value',goodNew.value );
  console.log('skus.value',skus.value)
  res.result.skus.forEach(sku=>{
    // console.log('sku',sku)
     if (sku.inventory > 0) {
      // 计算当前有库存的sku的子集
      // 例如：[1,2,3] ==> [[1],[2],[3],[1,2],[1,3],[2,3],[1,2,3]]
      // 可选值数组
      const valueArr = sku.specs.map(val => val.valueName)
      // 可选值数组 子集
      const valueArrPowerSet = powerSet(valueArr)
      console.log('valueArrPowerSet',valueArrPowerSet)
      // 遍历子集，往pathMap插入数据
      valueArrPowerSet.forEach(arr => {
        // 根据arr得到字符串的key，约定key是：['蓝色','美国'] ===> '蓝色★美国'
        const key = arr.join(spliter)
        // 给pathMap设置数据
        if (pathMap[key]) {
          pathMap[key].push(sku.id)
        } else {
          pathMap[key] = [sku.id]
        }
      })
    }

  })

}

// 获取已选中的值数组
const getSelectedValues = () => {
  const arr = []
  spes.value.forEach(item => {
    // 选中的按钮对象
    const seletedVal = item.values.find(val => val.selected)
    arr.push(seletedVal ? seletedVal.name : undefined)
  })
  return arr
}
// 更新按钮禁用状态
// 更新按钮禁用状态
const updateDisabledStatus = () => {
  // 1. 约定每一个按钮的状态由本身的disabled数据来控制
  spes.value.forEach((item, i) => {
    const selectedValues = getSelectedValues()
    item.values.forEach(val => {
      // 2. 判断当前是否选中，是选中不用判断
      if (val.selected) return
      // 3. 拿当前的值按照顺序套入选中的值数组
      selectedValues[i] = val.name
      // 4. 剔除undefined数据，按照分隔符拼接key
      const key = selectedValues.filter(value => value).join(spliter)
      // 5. 拿着key去路径字典中查找是否有数据，有可以点击，没有就禁用（true）
      val.disabled = !pathMap[key]
      // console.log('selectedValues',selectedValues)
    })
  })
}
// 默认选中
const initDefaultSelected = (goods, skuId) => {
  // 1. 找出sku的信息
  // 2. 遍历每一个按钮，按钮的值和sku记录的值相同，就选中。
  const sku = goods.skus.find(sku => sku.id === skuId)
  goods.specs.forEach((item, i) => {
    const val = item.values.find(val => val.name === sku.specs[i].valueName)
    val.selected = true
  })
}

const prev = () =>{
   console.log('prev')

}
const next = () =>{
   console.log('next')
}
 const activeName = ref('first')

const handleClick = (tab, event) => {
  console.log(tab, event)
}
const number = ref(1)
// 加入购物车
const addCar = async() =>{
  console.log('addCar')
  check()
  console.log(number.value)   
  store.dispatch('cart/insertCart',{
          skuId:good.skuId,
          attrsText:good.specsText,
          stock:good.inventory,
          id:goodNew.value.id,
          name:goodNew.value.name,
          price:good.price,
          nowPrice:good.price,
          picture:goodNew.value.mainPictures[0],
          selected: true,
          isEffective: true,
          count: number.value
  }).then(() => {
          ElMessage({
         showClose: true,
          message: '加入购物车成功',
          type: 'success',
  })
        })
      } 

  const  changNumber =(Carnumber) =>{
  console.log(Carnumber)
  number.value = Carnumber

}
const good = reactive({
  skuId: '',
  price: '',
  oldPrice: '',
  inventory: '',
  specsText:''
})

const changeSku = (item,i)=>{
  if (i.disabled) return
  // console.log(i.selected)
 if (i.selected) {
  i.selected = false
 }else{
   item.values.forEach(valItem => {
   valItem.selected = false
   console.log(valItem.selected)
 })
  i.selected = true
 }
          updateDisabledStatus()
          check()
  
}
// 加购物车前的规格是否完整
const check = () =>{
 console.log('getSelectedValues',getSelectedValues())
       const validSelectedValues = getSelectedValues().filter(v => v)
      if (validSelectedValues.length === spes.value.length) {
        // 完整
        console.log('validSelectedValues.length',validSelectedValues.length)
        const skuIds = pathMap[validSelectedValues.join(spliter)]
        const sku = skus.value.find(sku => sku.id === skuIds[0])
        good.skuId = sku.id
        good.price = sku.price
        good.oldPrice = sku.oldPrice
        good.inventory = sku.inventory
        good.specsText = sku.specs.reduce((p, c) => `${p} ${c.name}：${c.valueName}`, '').trim()
        console.log('good',good)
        console.log('可以加入购物车')

      }
      else{
        // alert('规格未完善！')
         console.log('good',good)
         console.log('请完善商品规格')
         ElMessage({
         showClose: true,
          message: '请完善商品规格',
          type: 'error',
  })
       
       
      }
}
// 获取商品详情
const useGoods = () => {
  // 出现路由地址商品ID发生变化，但是不会重新初始化组件
  const goods = ref(null)
  const route = useRoute()
  watch(() => route.params.id, (newVal) => {
    if (newVal && `/product/${newVal}` === route.path) {
      GoodsInfo(route.params.id).then(data => {
        // 让商品数据为null然后使用v-if的组件可以重新销毁和创建
        goods.value = null
        nextTick(() => {
          goods.value = data.result
        })
      })
    }
  })
}
 
getGoodsInfo();
 onMounted(() => {
      // 这个不行，不能访问methods对象
      // context.methods.loadMainPageIndex();
      // 还可以对data中的值进行修改，也可以促发自动更新到页面
      // console.log(ins.data.value1);
      updateDisabledStatus()
 })

   




</script>

<style lang="less" scoped>
.disabled {
    opacity: 0.6;
    border-style: dashed;
    cursor: not-allowed;
  }
.detail-img{
  text-align: center;
}
.detail-tag{
 min-width: 100px;
  color: #999999;
}
.detail-msg{
  color: #666;
}
.box{
  img{
    width: 50px;
    height: 50px;
  }
  
}
.el-tag{
  margin: 10px;
}
.a{ border:1px solid #1dc779 ;}
.selected{
  
    border:1px solid #1dc779 ;
    
}
.car{
  background-color: #27BA9B;
  font-size: 16px;
  padding: 10px;
  color: #fff;
}
.demo-tabs > .el-tabs__content {
  padding: 32px;
  height: 100%;
  color: #333;
  background-color:#fff;
  font-size: 32px;
  font-weight: 600;
}
.detail{
  padding: 20px;
    display: flex;
    flex-wrap: wrap;
    margin:0 0 30px;

    li{
    display: flex;
    padding: 10px;
    width: 50%;

    }
    .dd{
        flex: 1;
    color: #666;
    }
}
.el-tab-pane{
    min-height: 600px;
}
.goods-detal{
  
    width: 900px;
    margin: 20px 0;
    background-color:#fff;
}


.same{
    margin-left: 20px;
    display: flex;
    padding: 35px 50px;
    li{
        margin: 0 20px;
        width: 230px;
        height: 230px;
    }
    
}
.info{
    height: 380px;
    margin-top: 20px;
    background-color: #fff;
    padding: 20px;
   position: relative;
    h2{
        padding: 10px 0;
    }
    
    .left{
       position: absolute;
       top: 50%;
    }
    .right{
       position: absolute;
       top: 50%;
      right: 20px;
    }
}
.el-carousel__item h3 {
  color: #475669;
  opacity: 0.75;
  line-height: 300px;
  margin: 0;
  text-align: center;
}

.el-carousel__item:nth-child(2n) {
  background-color: #99a9bf;
}

.el-carousel__item:nth-child(2n + 1) {
  background-color: #d3dce6;
}
.number{
    span{ padding: 0 10px;display: inline-block;
    color: #999999;}
   p{
     display: inline-block;
     padding: 20px 20px;
   }
}
.type{
    padding: 20px 0;
    .box{
     display: inline-block;
     .img{
      display: inline-flex;
      align-items: center;
        text-align: center;
         width: 50px;
         height: 50px;
         border: 1px solid #E4E4E4;
          margin: 0 10px;
         img{
            width: 100%;
            height: 100%;
         }
         
     }
     .tag{
            display: inline-block;
            padding: 10px 20px;
              border: 1px solid #E4E4E4;
              margin: 0 10px;

         }

}
}
 .types{
        color: #999999;
        padding: 0 10px;
    }
.produceBox {
 
  background-color: #fff;
  width: 1240px;
  display: flex;
}
.produceImg {
 
  width: 580px;
  height: 600px;
  padding: 50px;
  display: flex;
  flex-wrap: wrap;
}
.active{
    border: 2px #1dc779 solid ;
}
.produceMsg {
  flex: 1;
  padding: 30px 30px 30px 0;

 
}
.bigImg {
  width: 400px;
  height: 400px;

  
  img{
    width: 100%;
    height: 100%;
  }
}
.small {
  width: 68px;
  height: 400px;


  li {
    margin: 10px 0;
    margin-left: 15px;
    width: 68px;
    height: 68px;
   
    cursor: pointer;
  }
  img{
    width: 100%;
    height: 100%;
  }
}
.goodsTag {
display: flex;
align-items: center;
  width: 400px;
  height: 140px;
  text-align: center;
 
  li{
   flex: 1;
    position: relative;
    padding: 5px;
  }
  p{
        font-size: 20px;
         color: #999999;
     }
     span{
  
    color: #cf4444;
   display: inline-block;
   padding: 10px 20px;
    border-right: 1px #999999 solid;

     }
     .p2{
   font-size: 14px;
   color: #333;
     }
}
.MsgBox{
    height: 150px;
    width: 500px;
   
     margin: 10px 0;
     background-color: #F5F5F5;
     dl{
       padding: 8px 0;
        margin: 15px 10px;
        p{
            display: inline-block;
            padding: 0 20px;
        }

     }
     
    
}
.service{
        span{
            padding: 10px 0;
        display: inline-block;
        }
     }
.produceMsg{
 .p1{
       line-height: 30px;
        font-size: 22px;
        color: #333333;
     }
     .p2{
        margin: 10px 0;
        color: #999999;
     }

}
.newPrice{
    font-size: 22px;
    color: #cf4444;
}
.olderPrice{
    font-size: 16px;
     color: #999999;
     margin-left: 10px;
text-decoration:line-through
}
li{
    list-style: none;
}
.el-cascader{
    background-color: #F5F5F5;
    
}

</style>